<?php
namespace app\community\controller;

use app\community\Controller;
use think\Db;
use think\Loader;
use think\Session;

Loader::import('controller/Controller', \think\Config::get('traits_path') , EXT);

class CaseGodown extends Controller
{
    use \app\community\traits\controller\Controller;
    // 方法黑名单
    protected static $blacklist = [];

    protected function init_select(){
        $role = Db::name('case_nature')->where(['isdelete'=>0,'ty_id'=>getTyId()])->field('id,nature')->order('id')->select()?:[];
        $html = '';
        foreach ( $role as $v ) {
            if( $this->request->param('cn_id') == $v['id'] ){
                $html .= '<option selected value="'.$v['id'].'">'.$v['nature'].'</option>';
                continue;
            }
            $html .= '<option value="'.$v['id'].'">'.$v['nature'].'</option>';
        }
        $this->view->assign("nature",$html );
        $role = Db::name('case_cate')->where(['isdelete'=>0,'ty_id'=>getTyId()])->field('id,cate')->order('id')->select()?:[];
        $html = '';
        foreach ( $role as $v ) {
            if( $this->request->param('cate_id') == $v['id'] ){
                $html .= '<option selected value="'.$v['id'].'">'.$v['cate'].'</option>';
                continue;
            }
            $html .= '<option value="'.$v['id'].'">'.$v['cate'].'</option>';
        }
        $this->view->assign("cate",$html );
        $role = Db::name('region')->where(['isdelete'=>0,'ty_id'=>getTyId()])->field('code_cn,code_en')->order('id')->select()?:[];
        $html = '';
        foreach ( $role as $v ) {
            if( $this->request->param('region') == $v['code_en'] ){
                $html .= '<option selected value="'.$v['code_en'].'">'.$v['code_cn'].'</option>';
                continue;
            }
            $html .= '<option value="'.$v['code_en'].'">'.$v['code_cn'].'</option>';
        }
        $this->view->assign("region",$html );

    }
    protected function filter($listRows=20,$isdelete=0,$asc=false){
        $this->init_select();

        $map = ['a.ty_id'=>getTyId(),'a.isdelete'=>$isdelete];
        $time = $this->request->param("from_time");
        if( $time ) {
            $time = explode(' - ',$time);
            2 === count($time,0) && $map['a.from_time'] = ["between", [strtotime($time[0]),strtotime($time[1])]];
        }
        $time = $this->request->param("create_time");
        if( $time ) {
            $time = explode(' - ',$time);
            2 === count($time,0) && $map['a.create_time'] = ["between", [strtotime($time[0]),strtotime($time[1])]];
        }
        $num1 = $this->request->param('num1');
        $num2 = $this->request->param('num2');
        if ( is_numeric($num1) && is_numeric($num2) ) {
            $map['a.people_num'] = ["between", [$num1,$num2]];
        } else if( is_numeric($num1) ) {
            $map['a.people_num'] = ["gt", $num1];
        } else if( is_numeric($num2) ) {
            $map['a.people_num'] = ["lt", $num2];
        }
        $num1 = $this->request->param('mon1');
        $num2 = $this->request->param('mon2');
        if ( is_numeric($num1) && is_numeric($num2) ) {
            $map['a.money'] = ["between", [$num1,$num2]];
        } else if( is_numeric($num1) ) {
            $map['a.money'] = ["gt", $num1];
        } else if( is_numeric($num2) ) {
            $map['a.money'] = ["lt", $num2];
        }
        if( -1 < $this->request->param('cn_id') ) {
            $map['a.cn_id'] = $this->request->param('cn_id');
        }
        if( -1 < $this->request->param('cate_id') ) {
            $map['a.cate_id'] = $this->request->param('cate_id');
        }
        if( $this->request->param('region') && '-1' !== $this->request->param('region') ) {
            $map['a.region'] = $this->request->param('region');
        }
        if( $this->request->param('from_user') ) {
            $map['a.from_user'] = ['like',"%{$this->request->param('from_user')}%"];
        }
        if( $this->request->param('input_name') ) {
            $map['a.input_name'] = ['like',"%{$this->request->param('input_name')}%"];
        }
        if( $this->request->param('sn') ) {
            $map['a.sn'] = ['like',"%{$this->request->param('sn')}%"];
        }

        //var_dump($map);exit;

        $model = Loader::model('community/CaseGodown');
        // 列表过滤器，生成查询Map对象
        // 排序字段 默认为主键名
        $order = $this->request->param('_order') ? : ($model->getPk());
        // 接受 sort参数 0 表示倒序 非0都 表示正序
        $sort = null !== $this->request->param('_sort')
            ? ($this->request->param('_sort') == 'asc' ? 'asc' : 'desc')
            : ($asc ? 'asc' : 'desc');
        $order_by = $order ? "{$order} {$sort}" : 'id desc';
        // 查询字段
        return $model->name('case_godown')->alias('a')->field('a.*,b.nature,c.cate')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id','left'],
                ['__CASE_CATE__ c','c.id=a.cate_id','left'],
            ])
            ->where($map)
            ->order($order_by)
            ->paginate($listRows, false, ['query' => $this->request->get()]);
    }
    /**
     * 首页
     * @return mixed
     */
    public function index() {
        $listRows = 20;
        $list = $this->filter($listRows,0);
        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign("page", $list->render());
        $this->view->assign("count", $list->total());
        $this->view->assign('numPerPage', $listRows);

        return $this->view->fetch();
    }

    public function daochu() {
        $asc=false;
        $map = ['a.ty_id'=>getTyId(),'a.isdelete'=>0];
        $time = $this->request->param("from_time");
        if( $time ) {
            $time = explode(' - ',$time);
            2 === count($time,0) && $map['a.from_time'] = ["between", [strtotime($time[0]),strtotime($time[1])]];
        }
        $time = $this->request->param("create_time");
        if( $time ) {
            $time = explode(' - ',$time);
            2 === count($time,0) && $map['a.create_time'] = ["between", [strtotime($time[0]),strtotime($time[1])]];
        }
        $num1 = $this->request->param('num1');
        $num2 = $this->request->param('num2');
        if ( is_numeric($num1) && is_numeric($num2) ) {
            $map['a.people_num'] = ["between", [$num1,$num2]];
        } else if( is_numeric($num1) ) {
            $map['a.people_num'] = ["gt", $num1];
        } else if( is_numeric($num2) ) {
            $map['a.people_num'] = ["lt", $num2];
        }
        $num1 = $this->request->param('mon1');
        $num2 = $this->request->param('mon2');
        if ( is_numeric($num1) && is_numeric($num2) ) {
            $map['a.money'] = ["between", [$num1,$num2]];
        } else if( is_numeric($num1) ) {
            $map['a.money'] = ["gt", $num1];
        } else if( is_numeric($num2) ) {
            $map['a.money'] = ["lt", $num2];
        }
        if( -1 < $this->request->param('cn_id') ) {
            $map['a.cn_id'] = $this->request->param('cn_id');
        }
        if( -1 < $this->request->param('cate_id') ) {
            $map['a.cate_id'] = $this->request->param('cate_id');
        }
        if( $this->request->param('region') && '-1' !== $this->request->param('region') ) {
            $map['a.region'] = $this->request->param('region');
        }
        if( $this->request->param('from_user') ) {
            $map['a.from_user'] = ['like',"%{$this->request->param('from_user')}%"];
        }
        if( $this->request->param('input_name') ) {
            $map['a.input_name'] = ['like',"%{$this->request->param('input_name')}%"];
        }
        if( $this->request->param('sn') ) {
            $map['a.sn'] = ['like',"%{$this->request->param('sn')}%"];
        }

        // 排序字段 默认为主键名
        $order = $this->request->param('_order') ? : false;
        // 接受 sort参数 0 表示倒序 非0都 表示正序
        $sort = null !== $this->request->param('_sort')
            ? ($this->request->param('_sort') == 'asc' ? 'asc' : 'desc')
            : ($asc ? 'asc' : 'desc');
        $order_by = $order ? "a.{$order} {$sort}" : 'a.id desc';

        $list = Db::name('case_godown')->alias('a')->field('a.id,a.region,a.from_user,a.from_mobile,FROM_UNIXTIME(a.from_time) as from_time,a.people_num,a.money,if(a.status>0, "是", "否") as status,a.sn,FROM_UNIXTIME(a.create_time) as create_time,a.input_name,a.end_state_txt,CASE WHEN a.state=1 THEN "待分配" WHEN a.state=2 THEN "进行中" WHEN a.state=3 THEN "已归档" ELSE "" END as state,a.remark,b.nature,c.cate,d.title as ty_name')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id','left'],
                ['__CASE_CATE__ c','c.id=a.cate_id','left'],
                ['__COMMUNITY__ d','d.id=a.ty_id','left'],
            ])
            ->where($map)
            ->order($order_by)
            ->select()?:[];
        
        if( count($list) > 10000 ){
            exit('数据量过大，请先缩小范围再导出数据');
        }

        $xlsCell = array(
            array('sn', '案件编号'),
            array('nature', '案件性质'),
            array('cate', '分类'),
            array('region', '区域编号'),
            array('from_user', '报案人'),
            array('from_mobile', '报案人电话'),
            array('from_time', '报案时间'),
            array('people_num', '涉案人数'),
            array('money', '涉案金额'),
            array('status', '是否冻结'),
            array('create_time', '录入时间'),
            array('input_name', '录入人'),
            array('state', '案件状态'),
            array('end_state_txt', '最终结果'),
            array('remark', '备注')
        );
        \app\lib\excel::exportExcelAJ("案件导出".date('Y_m_d_H_i_s'), $xlsCell, $list);
    }

    /**
     * 回收站
     */
    public function recycleBin() {
        $listRows = 20;
        $list = $this->filter($listRows,1);

        // 模板赋值显示
        $this->view->assign('list', $list);
        $this->view->assign("page", $list->render());
        $this->view->assign("count", $list->total());
        $this->view->assign('numPerPage', $listRows);
        return $this->view->fetch();
    }

    /**
     * 添加
     * @return mixed
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->except(['id'],'post');
            $data['ty_id'] = getTyId();
            $data['imgs'] = $this->request->post('imgs/a')?implode(',',$this->request->post('imgs/a')):'';
            $data['input_id'] = Session::get(\think\Config::get('rbac.user_auth_key'));
            $data['input_name'] = Session::get('real_name');
            $data['create_time'] = time();
            $data['from_time'] = strtotime($data['from_time'])?:time();

            // 简单的直接使用db写入
            Db::startTrans();
            try {
                Db::name('case_godown')->insert($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }


            return ajax_return_adv('添加成功');
        } else {
            // 添加
            $this->init_select();
            $this->view->assign("imgs", []);
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /**
     * 添加
     * @return mixed
     */
    public function edit()
    {
        if ($this->request->isAjax()) {
            // 插入
            $data = $this->request->post();
            if (!$data['id']) {
                return ajax_return_adv_error("缺少参数ID");
            }
            $id = $data['id'];
            unset($data['id']);
//            $data['input_id'] = Session::get(\think\Config::get('rbac.user_auth_key'));
//            $data['input_name'] = Session::get('real_name');
            $data['imgs'] = $this->request->post('imgs/a')?implode(',',$this->request->post('imgs/a')):'';
            $data['update_time'] = time();
            $data['from_time'] = strtotime($data['from_time'])?:time();
            // 简单的直接使用db写入
            Db::startTrans();
            try {
                Db::name('case_godown')->where(['id'=>$id,'ty_id'=>getTyId()])->update($data);
                // 提交事务
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return ajax_return_adv_error($e->getMessage());
            }

            return ajax_return_adv('添加成功');
        } else {
            $this->init_select();
            $id = $this->request->param('id');
            if (!$id) {
                throw new \HttpException(404, "缺少参数ID");
            }
            $vo = $this->getModel('case_godown')->where(['ty_id'=>getTyId(),'id'=>$id])->find();
            if (!$vo) {
                throw new \HttpException(404, '该记录不存在');
            }
            $vo['from_time'] = date('Y-m-d H:i:s',$vo['from_time']);
            $this->view->assign("vo", $vo);
            $this->view->assign("imgs", $vo['imgs']?explode(',',$vo['imgs']):[]);

            // 添加
            return $this->view->fetch(isset($this->template) ? $this->template : 'edit');
        }
    }

    /*查看详情*/
    public function details(){
        $id = $this->request->param('id');
        if (!$id) {
            throw new \HttpException(404, "缺少参数ID");
        }
        $vo = Db::name('case_godown')->alias('a')->field('a.*,b.nature,c.cate')
            ->join([
                ['__CASE_NATURE__ b','b.id=a.cn_id','left'],
                ['__CASE_CATE__ c','c.id=a.cate_id','left'],
            ])
            ->where(['a.ty_id'=>getTyId(),'a.id'=>$id])->find();
        if (!$vo) {
            throw new \HttpException(404, '该记录不存在');
        }
        $this->view->assign("vo", $vo);
        $this->view->assign("imgs", $vo['imgs']?explode(',',$vo['imgs']):[]);
        $this->view->assign("case_visitors", Db::name('case_visitors')->field('visitor,mobile,sex,idcard,address,update_time')->where(['case_id'=>$id])->select());
        $this->view->assign("case_company", Db::name('case_company')->field('company,mobile,sex,lxr,address,update_time')->where(['case_id'=>$id])->select());
        $this->view->assign("case_allot", Db::name('case_allot')->field('from_name,to_name,status,create_time,result_time,result_info')->where(['case_id'=>$id,'isdelete'=>0])->select());
        return $this->view->fetch();
    }

}
